package com.anhuanjia.tools.eao.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.util.StringUtils;

import com.anhuanjia.tools.eao.bean.EaoEngineer;
import com.anhuanjia.tools.eao.bean.EaoEngineerMember;
import com.anhuanjia.tools.eao.beanvo.EaoBasicInformationVo;
import com.anhuanjia.tools.eao.beanvo.EaoEngineerMemberVo;
import com.efastsoft.framework.Member;
import com.efastsoft.framework.UIFacade;
import com.efastsoft.framework.annotation.Alias;
import com.efastsoft.framework.annotation.Priv;
import com.efastsoft.framework.annotation.Priv.LoginType;
import com.efastsoft.framework.data.DataRow;
import com.efastsoft.framework.data.DataTable;
import com.efastsoft.framework.data.Q;
import com.efastsoft.framework.data.Transaction;
import com.efastsoft.framework.utility.StringUtil;

/**
 * 工程师库操作
 * 
 * @author
 *
 */
@Alias(value = "engineer")
public class EngineerUI extends UIFacade {
	/**
	 * 查询工程师列表
	 */
	@Priv(loginType = LoginType.Member)
	public List<EaoEngineerMemberVo> engineerList() {
		int pageSize = this.Request.getInt("PageSize");
		if (pageSize == 0) {
			pageSize = 10;
		}
		int pageIndex = this.Request.getInt("PageIndex");
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		List<EaoEngineerMemberVo> emList = new ArrayList<EaoEngineerMemberVo>();
		Set<Long> set = new HashSet<>();
		Q q = new Q("select count(1) as num from eao_engineer_member where ");
		Q q1 = new Q("select * from eao_engineer_member where ");
		if ("Ent".equals(Member.getType())) {
			q.append("Company = ?", Member.getUID());
			q1.append("Company = ?", Member.getUID());
		} else {
			q.append("Company = ?", Member.getCompany());
			q1.append("Company = ?", Member.getCompany());
		}
		DataTable dataTable = q.fetch();
		DataTable dataNum = q1.fetch(pageSize, pageIndex);
		for (DataRow dataRow : dataNum) {
			EaoEngineerMemberVo em = new EaoEngineerMemberVo();
			em.setMember(dataRow.getLong("Member"));
			em.setUserName(dataRow.getString("UserName"));
			em.setApplicant(dataRow.getString("Applicant"));
			em.setRegNumber(dataRow.getString("RegNumber"));
			em.setProfessionalNumber(dataRow.getString("ProfessionalNumber"));
			em.setRegisterClass(dataRow.getString("RegisterClass"));
			if (!StringUtils.isEmpty(dataRow.getDate("StartTime")))
				em.setStartTime(sf.format(dataRow.getDate("StartTime")).replaceAll("-", "."));

			if (!StringUtils.isEmpty(dataRow.getDate("EndTime")))
				em.setEndTime(sf.format(dataRow.getDate("EndTime")).replaceAll("-", "."));

			em.setIntegrityMessage(dataRow.getString("IntegrityMessage"));
			em.setProvince(dataRow.getString("Province"));
			em.setPermissions(dataRow.getInt("Permissions"));
			em.setRegNumberId(dataRow.getLong("RegNumberId"));
			em.setCompany(dataRow.getLong("Company"));
			em.setProjectNumber("");
			set.add(dataRow.getLong("Member"));
			emList.add(em);
		}
		Q q2 = new Q(
				" select au.Auditor,i.ReportType ,count(1) as bgb from eao_project_info as i LEFT JoIN eao_audit au on i.Id =au.ProjectId where (au.Stats = '未提交' or au.Stats = '审核中')");
		q2.and().in(" au.Auditor ", set);
		q2.append("GROUP BY i.ReportType , au.Auditor");
		DataTable table2 = q2.fetch();

		if (table2.getRowCount() > 0) {
			for (EaoEngineerMemberVo engineerMemberVo : emList) {
				String report_type = "";
				for (DataRow dataRow : table2) {
					if (dataRow.get(0).equals(engineerMemberVo.getMember().toString())) {
						String type = dataRow.getString("ReportType");
						if (StringUtils.isEmpty(type))
							type = "无分类";
						if (StringUtils.isEmpty(report_type)) {
							report_type = type + dataRow.getLong("bgb");
						} else {
							report_type += type + dataRow.getLong("bgb");
						}
					}
				}
				engineerMemberVo.setProjectNumbers(report_type);
			}
		}
		Q q3 = new Q(
				" select ps.StaffName, ReportType ,count(1) as bgb from eao_project_info as pi inner JOIN (select projectId , StaffName from eao_project_staff where ");
		q3.in(" StaffName ", set);
		q3.append(") as ps on ps.ProjectId =pi.Id where pi.PerjectType != '16' GROUP BY pi.ReportType ,ps.StaffName");
		DataTable table3 = q3.fetch();

		if (table3.getRowCount() > 0) {
			for (EaoEngineerMemberVo engineerMemberVo : emList) {
				String report_type = "";
				for (DataRow dataRow : table3) {
					if (dataRow.getString(0).equals(engineerMemberVo.getMember().toString())) {
						String type = dataRow.getString("ReportType");
						if (StringUtils.isEmpty(type))
							type = "无分类";
						if (StringUtils.isEmpty(report_type)) {
							report_type = type + dataRow.getLong("bgb");
						} else {
							report_type += type + dataRow.getLong("bgb");
						}
					}
				}
				engineerMemberVo.setProjectNumber(report_type);
			}
		}
		Integer total = 0;
		if (dataTable.getRowCount() > 0) {
			total = dataTable.get(0).getInt("num");
		}
		this.Response.put("emList", emList);
		this.Response.put("total", total);
		return emList;
	}

	/**
	 * 工程师库点击添加按钮显示
	 */
	@Priv(loginType = LoginType.Member)
	public void findMember() {
		Integer positionId = new Q(" select Id from eao_Position where Type = ? and ParentId = 7 ", Member.getCompany()).executeInt();
		this.Response.put("positionId",positionId);
		if(positionId == 0) {
			positionId = 7;
		}
		Q q = new Q(
				"SELECT re.Company as BranchId,re.Member as MemberId,po.id as PositionId,po.Position,me.RealName,me.Gender as Sex,rb.Name,rb.BranchInnerCode,rb.ParentInnerCode,rb.CompanyType,me.Mobile FROM Mh_Resource re left join Ec_Member AS me on re.Member = me.ID left join Mh_Branch AS rb on rb.Company = re.Company and rb.BranchInnerCode = re.BranchInnerCode left join eao_is_engineer eie on eie.Member = re.Member left join eao_Position po on po.Id = eie.IsEngineer where re.Company = ? and eie.IsEngineer <> ?",
				Member.getCompany() , positionId);
		q.and().append(" re.Member not in (select Member from eao_engineer_member where Company = ?)",
				Member.getCompany());
		DataTable dataTable = q.fetch();
		Set<String> set = new HashSet<>();
		if (dataTable.getRowCount() != 0) {
			List<EaoBasicInformationVo> list = new ArrayList<EaoBasicInformationVo>();
			for (DataRow dataRow : dataTable) {
				EaoBasicInformationVo information = new EaoBasicInformationVo();
				information.setMemberId(dataRow.getLong("MemberId"));
				information.setBrId(dataRow.getString("BranchInnerCode"));
				information.setPositionId(dataRow.getInt("PositionId"));
				information.setCompanyType(dataRow.getInt("CompanyType"));
				information.setPosition(dataRow.getString("position"));
				information.setRealName(dataRow.getString("RealName"));
				information.setMobile(dataRow.getString("Mobile"));
				information.setSex(dataRow.getString("Sex"));
				information.setBranch(dataRow.getString("Name"));
				information.setBranchInnerCode(dataRow.getString("BranchInnerCode"));
				information.setParentInnerCode(dataRow.getString("ParentInnerCode"));
				information.setCompanyType(dataRow.getInt("CompanyType"));
				information.setGs(dataRow.getString("Name"));
				information.setGsId(dataRow.getString("BranchId"));
				list.add(information);
				if (StringUtil.isEmpty(dataRow.getString("ParentInnerCode"))
						|| "0".equals(dataRow.getString("ParentInnerCode"))) {
					set.add(dataRow.getString("BranchInnerCode"));
				} else {
					set.add(dataRow.getString("ParentInnerCode"));
				}
			}

			DataTable dt = new Q("select * from Mh_Branch where 1 = 1").and().in("BranchInnerCode", set).and().eq("Company", Member.getCompany()).fetch();
			for (DataRow dataRow : dt) {
				for (EaoBasicInformationVo basicInformationVo : list) {
					if (dataRow.getString("BranchInnerCode").equals(basicInformationVo.getParentInnerCode())) {
						basicInformationVo.setGs(dataRow.getString("BranchInnerCode"));
						basicInformationVo.setGs(dataRow.getString("Name"));
					}
				}
			}
			this.Response.put("list", list);
		}
	}

	/**
	 * 工程师库点击确定
	 */
	@Priv(loginType = LoginType.Member)
	public void addMember() {
		Transaction t = new Transaction();
		String ids = $V("ids");
		String[] id = ids.split(",");
		Set<String> names = new HashSet<String>();
		Set<String> companys = new HashSet<String>();
		DataTable dt = new Q(
				"select mr.Member,mr.Company,cm.RealName,cc.FullName from Mh_Resource mr left join Crm_Company cc on mr.Company = cc.ID left join Ec_Member cm on mr.Member = cm.ID where ")
						.in("mr.Member", id).fetch();
		if (dt.getRowCount() > 0) {
			List<EaoEngineerMember> emList = new ArrayList<>();
			for (DataRow dataRow : dt) {
				EaoEngineerMember em = new EaoEngineerMember();
				em.setMember(dataRow.getLong("Member"));
				em.setUserName(dataRow.getString("RealName"));
				em.setCompany(dataRow.getLong("Company"));
				em.setApplicant(dataRow.getString("FullName"));
				emList.add(em);
				names.add(dataRow.getString("RealName"));
				companys.add(dataRow.getString("FullName"));
			}
			List<EaoEngineer> eList = new ArrayList<>();
			DataTable dt2 = new Q(" select * from eao_engineer where ").in("UserName", names).and()
					.in("Applicant", companys).fetch();
			if (dt2.getRowCount() > 0) {
				for (DataRow dataRow : dt2) {
					EaoEngineer e = new EaoEngineer();
					e.setValue(dataRow);
					eList.add(e);
				}
			}
			for (EaoEngineerMember engineerMember : emList) {
				for (EaoEngineer engineer : eList) {
					if (engineerMember.getUserName().equals(engineer.getUserName())) {
						engineerMember.setRegNumber(engineer.getRegNumber());
						engineerMember.setProfessionalNumber(engineer.getProfessionalNumber());
						engineerMember.setRegisterClass(engineer.getRegisterClass());
						engineerMember.setStartTime(engineer.getStartTime());
						engineerMember.setEndTime(engineer.getEndTime());
						engineerMember.setIntegrityMessage(engineer.getIntegrityMessage());
						engineerMember.setProvince(engineer.getProvince());
						engineerMember.setPermissions(engineer.getPermissions());
						engineerMember.setRegNumberId(engineer.getEngineerId());
					}
				}
				t.insert(engineerMember);
			}
			if (t.commit()) {
				s("添加成功");
			} else {
				f("添加失败");
			}

		} else {
			f("没有查到账户信息");
		}
	}

	/**
	 * 工程师库点击确定
	 */
	@Priv(loginType = LoginType.Member)
	public void deleteMember() {
		Transaction t = new Transaction();
		String ids = $V("Member");
		if(StringUtils.isEmpty(ids)) {
			f("操作失败");
		}
		String[] id = ids.split(",");
		List<String> member = new ArrayList<>();
		for (String string : id) {
			member.add(string);
		}
		Q dt = new Q("select * from eao_engineer_member where Company = ?", Member.getCompany());
		dt.and().in(" Member ", member);
		DataTable dataTable = dt.fetch();
		if (dataTable.getRowCount() != 0) {
			for (DataRow dataRow : dataTable) {
				EaoEngineerMember engineer = new EaoEngineerMember();
				engineer.setValue(dataRow);
				t.delete(engineer);
			}
			if (t.commit()) {
				s("删除成功");
			} else {
				f("删除失败");
			}

		} else {
			f("没有查到账户信息");
		}
	}
	
	/**
	 * 审核工程师权限修改
	 */
	@Priv(loginType = LoginType.Member)
	public void update() {
		String member = $V("Member");
		if (StringUtil.isNotEmpty(member)) {
			DataTable dataTable = new Q(" select * from eao_engineer_member where Member = ? ", member).fetch();
			if (dataTable.getRowCount() != 0) {
				EaoEngineerMember engineerMember = new EaoEngineerMember();
				engineerMember.setValue(dataTable.get(0));
				engineerMember.setValue(this.Request);
				if (engineerMember.update()) {
					s("操作成功");
				} else {
					f("操作失败");
				}
			} else {
				f("未找到对应的工程师信息");
			}
		} else {
			f("请选择你要修改的工程师");
		}
	}
}
